import React, { useState, useRef, FC, ReactElement } from 'react'
import classNames from 'classnames'

import { todoType } from '@/apis'
import { toggleTodo, removeTodo } from '@/store'

import less from './style.module.less'

const Item: FC<todoType> = ({
  id,
  content,
  done
}): ReactElement => {

  const [mouseFlag, setMouseFlag] = useState(false)
  const checkboxRef = useRef<HTMLInputElement>(null)

  // 是否删除
  const handleDelete = (id: number) => {
    if (window.confirm('确认删除吗？')) {
      removeTodo(id)
    }
  }

  return (
    <li
      className={less.item}
      style={{ backgroundColor: mouseFlag ? 'rgba(82, 168, 236, 0.3)' : '#fff' }}
      onMouseEnter={() => setMouseFlag(true)}
      onMouseLeave={() => setMouseFlag(false)}>
      <label>
        <input
          type="checkbox"
          ref={checkboxRef}
          checked={done}
          onChange={() => toggleTodo(id, checkboxRef.current!.checked)} />
        <span className={classNames({ [less.done]: done })}>{content}</span>
      </label>
      <button
        className={less.btn}
        style={{ display: mouseFlag ? 'block' : 'none' }}
        onClick={() => handleDelete(id)}>
        <span>删除</span>
      </button>
    </li>
  )
}

export default Item
